package com.hcms.common.service.impl;

import com.hcms.common.config.SpringMailProperties;
import com.hcms.common.service.IEmailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Date;

public class EmailServiceImpl implements IEmailService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private SpringMailProperties springMailProperties;

    @Override
    public void sendSimpleMail(String to, String subject, String content) {
        logger.info("Run sendSimpleMail(), to={}", to);
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(springMailProperties.getUsername());
        message.setTo(to.split(","));
        message.setSubject(subject);
        message.setText(content);
        message.setSentDate(new Date());
        javaMailSender.send(message);
        logger.info("Email sent successfully");
    }

    @Override
    public void sendHtmlMail(String to, String subject, String content) throws MessagingException {
        logger.info("Run sendHtmlMail(), to={}", to);
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(springMailProperties.getUsername());
        helper.setTo(to.split(","));
        helper.setSubject(subject);
        helper.setText(content, true);
        helper.setSentDate(new Date());
        javaMailSender.send(message);
        logger.info("Email sent successfully");
    }

    @Override
    public void sendAttachmentMail(String to, String subject, String content, String filePath) throws MessagingException {
        logger.info("Run sendAttachmentMail()");
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(springMailProperties.getUsername());
        helper.setTo(to.split(","));
        helper.setSubject(subject);
        helper.setText(content, true);
        helper.setSentDate(new Date());
        String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
        FileSystemResource resource = new FileSystemResource(filePath);
        helper.addAttachment(fileName, resource);
        javaMailSender.send(message);
        logger.info("Email sent successfully");
    }
}
